package Server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;


public class server extends Thread 
{
	Socket clientSocket = null;	
	BufferedReader In = null;
	PrintWriter out= null;
	int maxgroup = 100;
	
	public server(Socket client) 
	{
		clientSocket = client;
	}	
	
	public static void main(String[] args) throws UnknownHostException, IOException 
	{
		
		int port =15011;
		
        ServerSocket serverSocket = new ServerSocket(port);		
        System.out.println ("Server Waiting for a client on port " + port);
		int i=0;
		while(true) 
		{	     
			
			Socket connected = serverSocket.accept();
            (new server(connected)).start();
            i++;
		}      
		
	//	System.exit(0);

	}
	public void run() 
	{
		String[] arr= new String[2];
		try
		{
			In = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
			
		//	BufferedReader Inauth = new BufferedReader(new InputStreamReader(auths.getInputStream()));
			//accept the username@password
			String a=In.readLine();
			System.out.println(a);
			
			arr=a.split("@");
			//SPLIT and check
			
	//		PrintWriter outauth = new PrintWriter(new OutputStreamWriter(auths.getOutputStream()));
			if(arr[1].compareTo("aae")==0 )
			{
			out.println("1");
			out.flush();
			}
			else
				
			{
				out.println("0");
				out.flush();
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		
		String temp=null;
		int cl_id;
		
		
        try {
        	int flag=0;
        	cl_id = Integer.parseInt(arr[0]);
        	System.out.println("Client "+cl_id);
        	String ip= clientSocket.getInetAddress().getHostAddress();
        	String nullip="0.0.0.0";
        	int syn=0;
        	System.out.println("IP " + ip);
        	int [][] clients = new int[maxgroup][maxgroup*10];
        	int cid=1;
        	int gid=-1;
        	
        	BufferedReader list_s = new BufferedReader(new FileReader("./src/list_server_grps"));
        	//System.out.println(list_s.readLine());
        	
        	int tempnum;
        	while((temp=list_s.readLine())!=null)
        	{
        		//System.out.println("outer "+temp);
        		tempnum=Integer.parseInt(temp); 
        		//Integer.parseInt(temp);
        		if(tempnum!=0 && tempnum!=1)
        			{
        			gid++;
        			clients[gid][0]=tempnum;
        			}
        		
        		if(tempnum==0)
        		{
        			flag=1;
        			cid=1;
        		}
        		
        		if(flag==1)
        		{
        			flag=0;
        			while((Integer.parseInt(temp=list_s.readLine()))!=-1)
        				{//System.out.println("inner "+temp);
        				tempnum=Integer.parseInt(temp);
        				//System.out.println("check");
        				clients[gid][cid]=tempnum; //Integer.parseInt(temp);
        				cid++;
        				}
        		} 
        	}//groups found
        	
        	//for (int g=0;g<)
        	//System.out.println("check");
        	int tg=gid;
        	int[] currgrps = new int[10];
        	int cgi=0;
      //  	int auth=0;
        	int cl_id_num =cl_id;
        	System.out.println(cl_id_num);
        for(int k=0;k<tg;k++)
        {
        	for(int c=0;c<10;c++)
        	{
        		if(clients[k][c]!=0)
        			//System.out.println(clients[k][c]);
        		if(clients[k][c]==cl_id_num)
        		{
        //			auth=1;
        		//	System.out.println("Authorised");
        			currgrps[cgi]=clients[k][0];
        			System.out.println(currgrps[cgi]);
        			cgi++;
        		}
        	}
        }
        
        
       // if(auth==0)
        //	{
        	//	out.println("q");
        		//out.flush();
        		//System.exit(0);
        //	}
       // else
       // {
       
        	//out.println("User Authentication Successful");
        	//out.flush();
        	//syn=Integer.parseInt(In.readLine());
        	//stat=Integer.parseInt(In.readLine());       	 
       // }
        
        	System.out.println(ip);
        	
        	syn=1;
        	System.out.println(syn);
        Update(ip,syn,currgrps,cl_id);
        
        FR(cl_id,ip,currgrps,out);
        int i=0;
       // while(i<100)
       // {
       // 	System.out.println(ip);
        	try {
				Thread.sleep(30000000);//30000
			} catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
     //   }
        
        System.out.println("Current User is a part of following groups.");
        for(int c=0;c<10;c++)
    	{
        	if(currgrps[c]!=0)
        		System.out.println(currgrps[c]);
    	}
       	
		} catch (IOException e) 
		{
			e.printStackTrace();
		}
		
		
        System.err.println("Closing connection with client");
        out.close();
        try 
        {
			In.close();
		}
        catch (IOException e) 
        {
			e.printStackTrace();
		}
        try 
        {
			clientSocket.close();
		} 
        catch (IOException e) 
        {			
			e.printStackTrace();
		}
 	}

	private void FR(int cl_id,String ip, int [] grps,PrintWriter out) throws IOException 
	{
		//BufferedReader list_s = new BufferedReader(new FileReader("list_server_grps.txt"));
		//BufferedReader list_s = new BufferedReader(new FileReader("list_server.txt"));
		String nullip = "0.0.0.0";
		System.out.println(grps.length);
		for (int i=0;i< grps.length;i++)
		{
			BufferedReader list_s = new BufferedReader(new FileReader("./src/list_server.txt"));
			
			System.out.println("New group"+grps[i]);
			String temp;
			if(grps[i]==0)
			{
				continue;
			}
			while((temp=list_s.readLine()) != null)
			{
				
				if (temp.compareTo(Integer.toString(grps[i]))==0 )
				{
					System.out.println("Group Selected");
					out.println(grps[i]);
					out.flush();
					String temp2;
					while((temp2=list_s.readLine()).compareTo(Integer.toString(-2))!=0)
					{
						if (temp2.contains(".") && (temp2.compareTo(ip)!=0) && (temp2.compareTo(nullip)!=0))
						{
							System.out.println("Sending"+temp2);
							out.println(temp2);
							out.flush();
						}
					}
					System.out.println("group ended");
				//	out.println(0);
				//	out.flush();
				}
			}
			System.out.println("completed sending -1");
		//	out.println(-1);
		//	out.flush();
			list_s.close();

		}
		//list_s_ip.close();
		
		out.println("a");
		out.flush();
		

		
	}

	private void Update(String ip, int syn, int [] currgrps, int cl_id) throws IOException 
	{
		File F1= new File("./src/list_server.txt");
		BufferedReader list_s = new BufferedReader(new FileReader(F1));
		File F= new File("./src/out.txt");
		BufferedWriter list_s_w = new BufferedWriter(new FileWriter(F));

		String temp;
		//int tempnum;
		while((temp=list_s.readLine()) != null)
		{
			//tempnum=Integer.parseInt(temp);
			list_s_w.write(temp);
			//list_s_w.write("\n");
			list_s_w.newLine();
			if (temp.compareTo(Integer.toString(cl_id))==0 )
			{
				list_s.readLine();
				list_s_w.write(Integer.toString(syn));
				list_s_w.newLine();
				list_s.readLine();
				list_s_w.write("1");
				list_s_w.newLine();
				list_s.readLine();
				list_s_w.write(ip);
				//list_s_w.write("\n");
				list_s_w.newLine();
				
			}
		}
		list_s.close();
		list_s_w.close();
		// rename delete;
		F1.delete();
		F.renameTo(F1);		
	}
}